<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('mexico.semiFinishedProduct')" @clickRight="clickRight" scanType="1"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="barcodeSplitting">
				<!-- 扫描和库位选择模块 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedEnter.barcodeScan') }}
					</view>
					<!-- 调出仓库 -->
					<view class="custom-card-itemTwo" style="padding: 20rpx 0">
						<text class="item-info-title">{{ $t('translationImage.bringUpWarehouse') }}：</text>
						<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
							v-model="data.outWarehouseName" :placeholder="$t('pageTranslation.bringFromBarcode')" />
					</view>
					<!-- 调入仓库 -->
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title">{{ $t('translationImage.transferredWarehouse') }}：</text>
						<superweiCombox style="text-align:right;" :candidates="data.materialTransferListIn" v-if="!data.barcodeList.length"
							:placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="value"
							v-model="data.enterWarehouse" @select="materialTransferSelect"></superweiCombox>
						<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
							v-model="data.enterWarehouse" :placeholder="$t('pageTranslation.bringFromBarcode')" v-else/>
					</view>
					<!-- 调入库位 -->
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text
								class="required-color">*</text>{{ $t('translationImage.transferredSeat') }}：</text>
						<superweiCombox style="text-align:right;" :candidates="data.seatLocation" v-if="!data.barcodeList.length"
							:placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="value"
							v-model="data.currentSeat" @select="seatLocationClick"></superweiCombox>
						<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
							v-model="data.currentSeat" :placeholder="$t('mexico.automatically')"  v-else/>
					</view>

					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{ $t('distributedEnter.barcodeScan') }}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barcode" type="search"
							@confirm="confirm" @iconClick="iconClick"
							:placeholder="$t('translationImage.pleaseScanTray')">
						</uni-easyinput>
					</view>
				</view>
				<!-- card模块 -->
				<!-- <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll"> -->
				<view v-if="data.scanInfo" class="custom-form-card">
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('distributedOut.atPresent') }}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCoded')
										}}：</text>{{ data.scanInfo.barcode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCode')
										}}：</text>{{ data.scanInfo.materialCode
									}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialName')
										}}：</text>{{ data.scanInfo.materialName }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialSpec')
										}}：</text>{{ data.scanInfo.materialSpec }}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.qty')
											}}：</text>{{ data.scanInfo.currentQty }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.uom')
											}}：</text>{{ data.scanInfo.unit }}
									</view>
								</view>
								<view class="custom-card-itemOne" v-if="data.transferType != 'all'">
									<text class="item-info-title">{{
										$t('warehousing.transferQty')}}：</text>{{ (data.scanInfo.changeQty || 0) }}
								</view>
								<!-- <view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('translationImage.process') }}：</text>{{data.scanInfo.processCode}}
								</view> -->
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<!-- </scroll-view> -->

				<!-- 底部确定按钮 -->
				<view class="page-bottom-box bottom-postion">
					<!-- <view class="page-bottomBtn" @click="recommended" style="background-color:#3598DC;color:#fff;">{{ $t('materials.todaysRecommendedDosage') }}</view> -->
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCommit">{{ $t('calendar.submit')
						}}</view>
				</view>

			</view>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import comboGrid from '@/components/comboGrid.vue'
import pdaScan from '@/hooks/pdaScan.js'
import { useStore } from "vuex";
import storageBin from '@/components/storageBin.vue'
import superweiCombox from '@/components/superweiCombox';
import { submitTransferSemi, getIsUsePageSetPDA, semiScanTransferIn, scanSemiBarcode } from '@/api/api.js'
import { USERINFO, OPERATION_SEARCH, OPERATION_COMMIT, OPERATION_SCAN, DEFAULT_WAREHOUSECODE, BIGBARCODER_PRINT, DEFAULT_WAREHOUSEID } from '@/constant/index.js'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { onBackPress } from '@dcloudio/uni-app';
import { ref, reactive, onMounted, watch, computed, toRaw } from 'vue';
import { onShow } from '@dcloudio/uni-app';

//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

let inputDialog = ref(null)
let inputSplitDialog = ref(null)

components: {
	superweiCombox,
		storageBin,
		comboGrid
}
const storageBinRef = ref(null)
const comboGridRef = ref(null)
let store = useStore();
const { scan } = pdaScan()

let data = reactive({
	value: ['0'],
	scanInfo: undefined,
	barcode: '', //条码
	outWarehouseName: "",//调出仓库
	warehouseCode: '',//仓库code
	currentSeat: '', //调入库位
	currentSeatName: '',
	enterWarehouse: '',//调入仓库
	locationId: '',// 调入库位
	materialTransferList: [],
	materialTransferListIn: [],
	seatLocation: [],
	requestParam: {
		warehouseCode: ''
	},
	barcodeList: [],//扫描的条码数组
	defaultValue: '', //打印机名字
})

onShow(async () => {
	data.outWarehouseName = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || ''
	data.requestParam.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || ''
	data.defaultValue = uni.getStorageSync(BIGBARCODER_PRINT) || ''
	if (!data.outWarehouseName.length) {
		alertDialogOpen()
	}
	if (data.defaultValue == '') {
		uni.showModal({
			content: t('JsInternational.plsPrinter'),
			showCancel: false,
			confirmText: t('pageTranslation.toSet'),
			success: function (res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/setting/printer'
					})
				} else if (res.cancel) {

				}
			}
		});
	}
})
onMounted(() => {
	uni.$on('scancodedate', (data) => {
		// console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	outWarehouse()
})


const alertDialogOpen = () => {
	uni.showModal({
		content: t('pageTranslation.noDefaultLocation'),
		showCancel: false,
		title: t('smashRemoval.warmPrompt'),
		confirmText: t('pageTranslation.toSet'),
		success: function (res) {
			if (res.confirm) {
				uni.navigateTo({
					url: '/pages/setting/warehouse'
				})
			} else if (res.cancel) {

			}
		}
	});
}

// 调入仓库获取
const outWarehouse = async () => {
	await getIsUsePageSetPDA({
		warehouseName: '',
		warehouseCode: '',
		size: 20,
		current: 1
	}).then(res => {
		if (res.code == 0) {
			data.materialTransferList = res.data.records
			if (res.data.records.length) {

				for (let i = 0; i < data.materialTransferList.length; i++) {
					if (data.materialTransferList[i].warehouseCode == data.outWarehouseName) {

					} else {
						if (data.materialTransferList[i].warehouseCode != 'SP') {
							data.materialTransferListIn.push({
								value: data.materialTransferList[i].warehouseCode,
								label: data.materialTransferList[i].warehouseCode,
								name: data.materialTransferList[i].warehouseName,
								id: data.materialTransferList[i].id
							})
						}

					}

				}
				if (!data.materialTransferListIn.length) return
				data.warehouseText = data.materialTransferListIn[0].value;
				data.requestParam.warehouseCode = data.materialTransferListIn[0].value  // 默认选中第一个 value
				data.warehouseCode = data.materialTransferListIn[0].value
			}
		}
	});
}

// 选择调入仓库 取出相对的库位code
const materialTransferSelect = (e) => {
	data.enterWarehouse = e.value
	data.currentSeat = ''
	semiScanTransferIn({
		warehouseCode: e.value
	}).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '半成品调拨'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SEARCH,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res.data)
		if (res.code == 0) {
			if (res.data.length) {
				res.data.forEach(item => {
					data.seatLocation.push({
						label: item.locationCode,
						value: item.locationCode,
						name: item.locationName
					})
				})
			}
			// data.currentSeat=res.data[0].locationCode
			// data.currentSeatName=res.data[0].locationName
		}
	})
}

// 选择库位
const seatLocationClick = (e) => {
	data.currentSeat = e.value
}

data.barcodeList = computed(() => {
	return store.state.semiFinished
})

//把扫描条码变为物料集合的二维数组
watch(() => data.barcodeList, (newVal, oldVal) => {
	console.log('newVal, oldVal', newVal, oldVal)
	// calculateLocationCode(newVal)
}, {
	immediate: true,
	deep: true
});

// 用户点击扫码图标
const iconClick = async (type) => {
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击搜索
const confirm = () => {
	getCode(data.barcode, 'keydown')
}

// 获取code
const getCode = (code, type) => {
	let isBind = data.barcodeList.some(x => x.barcode == code);
	if (isBind) {
		uni.showToast({
			title: t('JsInternational.scanned'),
			icon: 'none'
		})
		return
	}
	if (!data.enterWarehouse) {
		uni.showToast({
			title: t('pageTranslation.plsChooseWarehous'),
			icon: 'none'
		})
		return
	}
	if (!code) {
		uni.showToast({
			title: t('stockManage.pleaseScanCode'),
			icon: 'none'
		})
		return
	}
	data.barcode = code
	let parmes = {
		// isSp: 0,
		OutWarehouseCode: data.outWarehouseName, // 调出仓库
		warehouseCode: data.enterWarehouse,//调入仓库
		locationCode: data.currentSeat,//调入库位
		barcode: code,
		transferType: '',
	}
	scanSemiBarcode(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '原材料调拨'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			let isBind = data.barcodeList.some(x => x.barcode == res.data.barcode);
			if (isBind) {
				uni.showToast({
					title: t('pageTranslation.theBarcodeAlready'),
					icon: 'none'
				})
				return
			}
			data.scanInfo = res.data
			data.scanInfo.enterWarehouse = data.enterWarehouse,//调入仓库
				data.scanInfo.currentSeat = data.currentSeat,//调入库位
				data.scanInfo.changeQty = res.data.currentQty
			store.commit('addSemiFinished', data.scanInfo)
		} else {
			data.scanInfo = undefined
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}


//扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/semiFinishedProduct/semiFinishedProductRecord'
	})
}

// 提交操作
const handelCommit = () => {
	if (!data.barcodeList.length) {
		uni.showToast({
			title: t('stockManage.pleaseScanCode'),
			icon: 'none'
		})
		return
	}
	let tepData = toRaw(data.barcodeList)
	// console.log(tepData, '----tepData----')
	let parmes = []
	tepData.forEach(x => {
		// console.log(x)
		parmes.push({
			outWarehouseCode: x.warehouseCode,
			barcode: x.barcode,
			qty: x.qty,
			remark:'PDA',
			warehouseCode: x.enterWarehouse,
			locationCode: x.currentSeat,
			transferType: 'AllTransfer',//调拨类型
			printName: data.defaultValue
		})
	})
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	//提交接口
	submitTransferSemi(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '半成品调拨'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res)
		if (res.code == 0) {
			//隐藏加载框
			uni.hideLoading();
			//删除已提交的数据
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			store.commit('reactSemiFinished')
			// 清空数据
			// data.outWarehouseName = "";
			data.enterWarehouse = "";
			data.currentSeat = "";
			data.barcode = "";
			data.scanInfo = {}

		} else {
			uni.showToast({ title: res.msg, icon: "none" });
			return
		}
	});

}


onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.barcodeList.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					store.commit('reactSemiFinished')
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.barcodeList.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.clearedIfReturned'),
		success: function (res) {
			if (res.confirm) {
				store.commit('reactSemiFinished')
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}

</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.page-bottom-box {
	position: absolute;
	left: 0px;
	bottom: 0px;
	width: 100%;
}

.item-color {
	color: #000;
	font-weight: bold;
}

.group {
	display: flex;
	flex-direction: row;

	.group-label {
		width: 230rpx;
		display: flex;
		flex-direction: row;
	}

	.lable-view {
		width: 70rpx;
		height: 100%;
	}
}
</style>
